<template>
    <div class="meeting-detail">
        <!-- 头部导航 -->
        <header class="header">
                <div class="back-btn" @click="handleBack">
                    <el-icon>
                        <ArrowLeft />
                    </el-icon>
                    <span>返回</span>
                </div>
                <h1>签到详情</h1>
                <Time />
        </header>

        <div class="main-container" style="padding-top: 180px;">
            <div class="form-container"  v-loading="loading" element-loading-text="加载中..." element-loading-background="rgba(0,0,0,0)">
                <!-- 签到题目 -->
                <div class="form-item">
                    <label>签到题目</label>
                    <template v-if="isEditing">
                        <input v-model="editForm.title" placeholder="请输入签到题目" />
                    </template>
                    <template v-else>
                        <div class="detail-text">{{ signDetail.meetingInfo?.title }}</div>
                    </template>
                </div>

                <!-- 签到简介 -->
                <div class="form-item">
                    <label>签到简介</label>
                    <template v-if="isEditing">
                        <textarea v-model="editForm.introduction" rows="4" placeholder="请输入签到简介" style="font-family: '微软雅黑';width: 97.5%;"></textarea>
                        <div class="word-count">{{ editForm.introduction.length }}/200</div>
                    </template>
                    <template v-else>
                        <div class="detail-text description">{{ signDetail.meetingInfo?.introduction }}</div>
                    </template>
                </div>

                <!-- 主办方和签到时间在同一行 -->
                <div class="form-row">
                    <div class="form-item">
                        <label>主办方</label>
                        <template v-if="isEditing">
                            <input v-model="editForm.organizer" placeholder="请输入主办方" />
                        </template>
                        <template v-else>
                            <div class="detail-text">{{ signDetail.meetingInfo?.organizer }}</div>
                        </template>
                    </div>

                    <div class="form-item date-picker-group">
                        <label>签到时间</label>
                        <template v-if="isEditing">
                            <div class="date-range-wrapper">
                                <el-date-picker 
                                    v-model="dateRange[0]" 
                                    type="datetime" 
                                    placeholder="开始日期时间" 
                                    class="date-picker"
                                    format="YYYY-MM-DD HH:mm"
                                    value-format="YYYY-MM-DD HH:mm"
                                />
                                <span class="separator">至</span>
                                <el-date-picker 
                                    v-model="dateRange[1]" 
                                    type="datetime" 
                                    placeholder="结束日期时间" 
                                    class="date-picker"
                                    format="YYYY-MM-DD HH:mm"
                                    value-format="YYYY-MM-DD HH:mm"
                                />
                            </div>
                        </template>
                        <template v-else>
                            <div class="detail-text">
                                {{ formatDate(signDetail.meetingInfo?.startTime) }} 至 
                                {{ formatDate(signDetail.meetingInfo?.endTime) }}
                            </div>
                        </template>
                    </div>
                </div>

                <!-- 签到地点和具体地点 -->
                <div class="location-row">
                    <div class="form-item">
                        <label>签到地点</label>
                        <template v-if="isEditing">
                            <div class="location-input-wrapper">
                                <el-input
                                    v-model="editForm.location1"
                                    placeholder="请输入签到地点"
                                    @input="handleLocationSearch"
                                    class="location-input"
                                />
                                <div v-show="searchResults.length > 0" class="location-suggestions">
                                    <div
                                        v-for="(item, index) in searchResults"
                                        :key="index"
                                        class="suggestion-item"
                                        @click="selectLocation(item)"
                                    >
                                        <span class="name">{{ item.name }}</span>
                                        <span class="address">{{ item.address }}</span>
                                    </div>
                                </div>
                            </div>
                        </template>
                        <template v-else>
                            <div class="detail-text">{{ signDetail.meetingInfo?.location1 }}</div>
                        </template>
                    </div>
                    <div class="form-item">
                        <label>具体地点</label>
                        <template v-if="isEditing">
                            <input v-model="editForm.location2" placeholder="请输入具体地点" />
                        </template>
                        <template v-else>
                            <div class="detail-text">{{ signDetail.meetingInfo?.location2 }}</div>
                        </template>
                    </div>
                </div>

                <!-- 参与人列表 -->
                <div class="form-item">
                    <label>参与人名单</label>
                    <div class="participants-list">
                        <template v-if="isEditing">
                            <div class="invite-section">
                                <el-input 
                                    v-model="searchKeyword" 
                                    placeholder="支持搜索姓名、手机号、所属单位、ID" 
                                    class="search-input"
                                    @keyup.enter="handleSearch"
                                >
                                    <template #suffix>
                                        <el-icon class="search-icon" @click="handleSearch">
                                            <Search />
                                        </el-icon>
                                    </template>
                                </el-input>

                                <div class="filter-section">
                                    <el-select v-model="filters.identity" placeholder="身份" class="filter-item">
                                        <el-option label="身份筛选：全部" value="all" />
                                        <el-option label="市级政协委员" value="city" />
                                    </el-select>
                                    <el-select v-model="filters.region" placeholder="地区" class="filter-item">
                                        <el-option label="地区筛选：全部" value="all" />
                                    </el-select>
                                    <el-select v-model="filters.affiliation" placeholder="界别" class="filter-item">
                                        <el-option label="界别筛选：全部" value="all" />
                                    </el-select>
                                    <el-button 
                                        type="danger" 
                                        @click="addSelectedParticipants"
                                        :disabled="currentSelection.length === 0"
                                    >
                                        添加所选
                                    </el-button>
                                </div>

                                <el-table 
                                    ref="participantsTable"
                                    :data="participantsList" 
                                    @selection-change="handleSelectionChange"
                                    class="participants-table"
                                    v-loading="participantsLoading"
                                >
                                    <el-table-column type="selection" width="55" :selectable="(row) => !isParticipantSelected(row)" />
                                    <el-table-column prop="uname" label="姓名" />
                                    <el-table-column prop="identity" label="身份" />
                                    <el-table-column prop="region" label="地区" />
                                    <el-table-column prop="affiliation" label="界别" />
                                </el-table>
                            </div>

                            <div class="selected-participants">
                                <el-table 
                                    :data="editForm.participants"
                                    @selection-change="handleSelectedListChange"
                                    class="selected-table"
                                >
                                    <el-table-column width="55">
                                        <template #header>
                                            <span>{{ editForm.participants.length }}人</span>
                                        </template>
                                        <template #default="scope">
                                            <el-icon 
                                                :class="['delete-icon', { 'selected': scope.row.isSelected }]"
                                                @click="toggleParticipantSelection(scope.row)"
                                                style="cursor: pointer;"
                                            >
                                                <Delete />
                                            </el-icon>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="uname" label="姓名" />
                                    <el-table-column prop="identity" label="身份" />
                                    <el-table-column prop="region" label="地区" />
                                    <el-table-column prop="affiliation" label="界别" />
                                    <el-table-column width="120">
                                        <template #header>
                                            <el-button 
                                                type="danger" 
                                                size="small" 
                                                @click="removeSelectedParticipants"
                                                :disabled="!hasSelectedToRemove"
                                            >
                                                删除所选
                                            </el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </template>
                        <template v-else>
                            <el-table :data="signDetail.participants" class="participants-table">
                                <el-table-column prop="uname" label="姓名" />
                                <el-table-column prop="phone" label="手机号" />
                                <el-table-column prop="identity" label="身份" />
                                <el-table-column prop="region" label="地区" />
                                <el-table-column prop="affiliation" label="界别" />
                                <el-table-column prop="mpStatus" label="签到状态">
                                    <template #default="scope">
                                        <span :class="{'signed': scope.row.mpStatus === '已签到'}">
                                            {{ scope.row.mpStatus }}
                                        </span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </template>
                    </div>
                </div>
            </div>

            <!-- 底部按钮 -->
            <div class="form-actions">
                <template v-if="isEditing">
                    <el-button @click="cancelEdit">取消</el-button>
                    <el-button type="danger" @click="submitEdit">保存</el-button>
                </template>
                <template v-else>
                    <el-button v-if="allowEdit" type="danger" @click="startEdit">修改</el-button>
                </template>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft, Search, Delete } from '@element-plus/icons-vue'
import { getSignDetail, getParticipants, updateSign } from '@/api/sign'
import { ElMessage, ElMessageBox } from 'element-plus'
import AMapLoader from '@amap/amap-jsapi-loader'
import Time from '@/components/Time.vue'
import { useSignsStore } from '@/stores/signs'
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const participantsLoading = ref(false)
const signsStore = useSignsStore()
const signDetail = ref({})
const isEditing = ref(false)
const searchResults = ref([])
const searchKeyword = ref('')
const participantsList = ref([])
const currentSelection = ref([])
const selectedToRemove = ref([])
const participantsTable = ref(null)
const dateRange = ref([])
const filters = ref({
    identity: 'all',
    region: 'all',
    affiliation: 'all'
})

let autoComplete = null

// 编辑表单
const editForm = ref({
    title: '',
    introduction: '',
    organizer: '',
    location1: '',
    location2: '',
    participants: []
})

// 添加一个计算属性来判断是否允许编辑
const allowEdit = computed(() => {
    return route.query.from !== 'ended'
})

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 初始化高德地图
const initAMap = async () => {
    try {
        window._AMapSecurityConfig = {
            securityJsCode: '471c055f43738d0a48758620c81ed465',
        }
        
        await AMapLoader.load({
            key: '6b8b624eb7c617e7c16e2eb2941b2081',
            version: '2.0',
            plugins: ['AMap.AutoComplete']
        })
        
        autoComplete = new AMap.AutoComplete({
            city: '全国'
        })
    } catch (error) {
        console.error('地图初始化失败:', error)
    }
}

// 处理地址搜索
const handleLocationSearch = async (value) => {
    if (!value) {
        searchResults.value = []
        return
    }
    
    try {
        if (!autoComplete) return
        
        autoComplete.search(value, (status, result) => {
            if (status === 'complete' && result.tips) {
                searchResults.value = result.tips.map(tip => ({
                    name: tip.name,
                    address: tip.district + tip.address,
                    location: tip.location,
                    district: tip.district
                }))
            }
        })
    } catch (error) {
        console.error('地址搜索失败:', error)
    }
}

// 选择地址
const selectLocation = (item) => {
    editForm.value.location1 = item.name
    editForm.value.location2 = item.address
    searchResults.value = []
}

// 获取签到详情
const fetchSignDetail = async () => {
    loading.value = true
    try {
        const mid = route.params.sid  // 路由参数中的sid实际上是mid
        console.log('Fetching sign detail for mid:', mid)
        
        const response = await getSignDetail(mid)
        console.log('API Response:', response)
        
        if (response.code === 200) {
            signDetail.value = response.data
            // 初始化编辑表单
            initEditForm()
        } else {
            ElMessage.error(response.msg || '获取签到详情失败')
        }
    } catch (error) {
        console.error('获取签到详情失败:', error)
        ElMessage.error('获取签到详情失败')
    } finally {
        loading.value = false
    }
}

// 初始化编辑表单
const initEditForm = () => {
    const info = signDetail.value.meetingInfo
    if (!info) return

    editForm.value = {
        mid: info.mid,  // 使用mid而不是sid
        title: info.title,
        introduction: info.introduction,
        organizer: info.organizer,
        location1: info.location1,
        location2: info.location2,
        participants: signDetail.value.participants || []
    }

    // 处理日期格式
    dateRange.value = [
        info.startTime.substring(0, 16), // 只取到分钟
        info.endTime.substring(0, 16)
    ]
}

// 开始编辑
const startEdit = () => {
    isEditing.value = true
    initEditForm()
}

// 取消编辑
const cancelEdit = () => {
    ElMessageBox.confirm('确定要取消编辑吗？未保存的修改将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        isEditing.value = false
        initEditForm()
    }).catch(() => {})
}

// 提交编辑
const submitEdit = async () => {
    try {
        const updateData = {
            mid: editForm.value.mid,  // 使用mid而不是sid
            title: editForm.value.title,
            introduction: editForm.value.introduction,
            organizer: editForm.value.organizer,
            startTime: dateRange.value[0],
            endTime: dateRange.value[1],
            location1: editForm.value.location1,
            location2: editForm.value.location2,
            participantIds: editForm.value.participants.map(p => p.uid),
            isMeeting: false  // 添加标识,表明这是签到而不是会议
        }

        const response = await updateSign(updateData)
        if (response.code === 200) {
            ElMessage.success('修改成功')
            isEditing.value = false
            fetchSignDetail()
            signsStore.fetchSigns()
        } else {
            ElMessage.error(response.msg || '修改失败')
        }
    } catch (error) {
        console.error('修改失败:', error)
        ElMessage.error('修改失败')
    }
}

// 获取参与者列表
const fetchParticipants = async () => {
    participantsLoading.value = true
    try {
        const response = await getParticipants({
            searchText: searchKeyword.value,
            identity: filters.value.identity === 'all' ? '' : filters.value.identity,
            region: filters.value.region === 'all' ? '' : filters.value.region,
            affiliation: filters.value.affiliation === 'all' ? '' : filters.value.affiliation
        })
        if (response.code === 200) {
            participantsList.value = response.data
        } else {
            ElMessage.error(response.msg || '获取参与者列表失败')
        }
    } catch (error) {
        console.error('获取参与者列表错误:', error)
        ElMessage.error('获取参与者列表失败')
    } finally {
        participantsLoading.value = false
    }
}

// 搜索参与者
const handleSearch = () => {
    fetchParticipants()
}

// 判断参与者是否已被选中
const isParticipantSelected = (participant) => {
    return editForm.value.participants.some(p => p.uid === participant.uid)
}

// 处理选择变化
const handleSelectionChange = (val) => {
    currentSelection.value = val
}

// 添加所选参与者
const addSelectedParticipants = () => {
    if (currentSelection.value.length === 0) return
    
    const newParticipants = currentSelection.value.map(item => ({
        ...item,
        isSelected: false
    }))
    
    editForm.value.participants = [...editForm.value.participants, ...newParticipants]
    currentSelection.value = []
    
    if (participantsTable.value) {
        participantsTable.value.clearSelection()
    }
}

// 处理参与者名单的选择变化
const handleSelectedListChange = (val) => {
    selectedToRemove.value = val
}

// 移除选中的参与者
const removeSelectedParticipants = () => {
    if (selectedToRemove.value.length === 0) {
        ElMessage.warning('请先选择要删除的参与者')
        return
    }
    
    editForm.value.participants = editForm.value.participants.filter(item => 
        !selectedToRemove.value.some(selected => selected.uid === item.uid)
    )
    
    selectedToRemove.value = []
}

// 切换参与者选择状态
const toggleParticipantSelection = (participant) => {
    participant.isSelected = !participant.isSelected
    if (participant.isSelected) {
        if (!selectedToRemove.value.some(p => p.uid === participant.uid)) {
            selectedToRemove.value.push(participant)
        }
    } else {
        selectedToRemove.value = selectedToRemove.value.filter(p => p.uid !== participant.uid)
    }
}

const hasSelectedToRemove = computed(() => {
    return selectedToRemove.value.length > 0
})

// 返回上一页
const handleBack = () => {
    if (isEditing.value) {
        ElMessageBox.confirm('确定要离开吗？未保存的修改将会丢失', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            router.back()
        }).catch(() => {})
    } else {
        router.back()
    }
}

onMounted(() => {
    fetchSignDetail()
    initAMap()
    fetchParticipants()
})
</script>

<style scoped>
@import '@/assets/css/meeting/addMeeting.css';
@import '@/assets/css/header/index.css';
.meeting-detail {
    height: 100%;
    overflow-y: auto;
}

.detail-text {
    padding: 8px 12px;
    background-color: #ffffff;
    border-radius: 4px;
    min-height: 20px;
    line-height: 1.5;
}

.detail-text.description {
    min-height: 80px;
    white-space: pre-wrap;
}

.sign-stats {
    display: flex;
    gap: 20px;
    margin-top: 10px;
}

.stat-item {
    display: flex;
    align-items: center;
    gap: 5px;
}

.stat-item .label {
    color: #606266;
}

.stat-item .value {
    font-weight: bold;
    color: #303133;
}

.signed {
    color: #67c23a;
}

.participants-list {
    margin-top: 10px;
}

.participants-table {
    width: 100%;
}

.form-actions {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 20px;
    padding: 20px 0;
}

.invite-section {
    margin-bottom: 20px;
}

.filter-section {
    margin: 15px 0;
    display: flex;
    gap: 10px;
}

.filter-item {
    width: 150px;
}

.selected-participants {
    margin-top: 20px;
}
</style>
